package main

// 优雅的通知子gorutine退出 利用全局变量
import (
	"context"
	"fmt"
	"sync"
	"time"
)

func f(ctx context.Context) {
	defer wg.Done()
	var n int = 0
	go f2(ctx)
LOOP:
	for {
		n++
		fmt.Println("## ", n)
		select {
		case <-ctx.Done():
			break LOOP
		default:
		}
		time.Sleep(1 * time.Second)
	}
}
func f2(ctx context.Context) {
	defer wg.Done()
	var n int = 0
LOOP:
	for {
		n++
		fmt.Println("@@ ", n)
		select {
		case <-ctx.Done():
			break LOOP
		default:
		}
		time.Sleep(1 * time.Second)
	}
}

var wg sync.WaitGroup

func main() {
	ctx, canael := context.WithCancel(context.Background())
	wg.Add(1)
	go f(ctx)
	time.Sleep(5 * time.Second)
	canael()
	wg.Wait() //阻塞

}
